package com.changgou.oauth2.service;

import com.changgou.oauth2.pojo.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * 老大哥在看着你
 *
 * @author ANG.YU
 * @date 2019-10-20 22:52
 */
@Service
public class LoginServiceImpl {
    @Autowired
    /*注入负载均衡客户端*/
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    public AuthToken login(String username, String password, String clientId, String clientSecret) {
        ServiceInstance serviceInstance = loadBalancerClient.choose("user-auth");
        /*最终访问的地址： * http://localhost:9200/oauth/token */
       String url = serviceInstance.getUri() + "/oauth/token";

        LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap();
        headers.add("Authorization", handlerHttpHeader(clientId, clientSecret));

        LinkedMultiValueMap body = new LinkedMultiValueMap();
        body.add("grant_type", "password");
        body.add("username", username);
        body.add("password", password);


        HttpEntity<LinkedMultiValueMap<String, String>> requestEntity = new HttpEntity(body, headers);

        ResponseEntity<Map> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Map.class);
        Map entityBody = responseEntity.getBody();
        AuthToken authToken = new AuthToken();
        authToken.setRefreshToken(String.valueOf(entityBody.get("refresh_token")));
        authToken.setJti(String.valueOf(entityBody.get("jti")));
        authToken.setAccessToken(String.valueOf(entityBody.get("access_token")));

        return authToken;
    }

    private String handlerHttpHeader(String clientId, String clientPassword) {
        String s = clientId + ":" + clientPassword;
        byte[] encode = Base64Utils.encode(s.getBytes());
        return "Basic " + new String(encode);
    }
}
